package cn.semyes.simi.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bcloud.msg.http.HttpSender;
import com.google.gson.JsonObject;

import cn.semyes.simi.bean.OrderConstants;
import cn.semyes.simi.bean.SmsConstants;




public class BusinessUtils {
	
	public static final  String HTTP_PATTERN = "^http://|/$"; //过滤掉 http 与 /结尾的http表达式
	public static final String WWW_PATTERN ="^www."; //过滤掉域名里面www的开头
	
	private static Logger log = Logger.getLogger("BusinessUtils.class");

	 public static String getRandomPassword(){
		 String s = String.valueOf(System.currentTimeMillis() + new Random().nextInt());
		 return s;
	 }
    /**
     * 返回系统当前时间(精确到毫秒)+UUID,作为一个唯一的编号
     * @return  以yyyyMMddHHmmssSSS为格式的当前系统时间
     */
	public static String getUniqueNum(){
		Date date=new Date();
		DateFormat df=new SimpleDateFormat("yyyyMMddHHmmssSSS");		
		String orderNum = df.format(date) + UUID.randomUUID().toString().hashCode();
		return orderNum;
	}	
	
	/**
	 * 获取客户端IP
	 * @param request
	 * @return
	 */
	public static String getRemoteHostIP(javax.servlet.http.HttpServletRequest request){
	    String ip = request.getHeader("x-forwarded-for");
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
	        ip = request.getHeader("Proxy-Client-IP");
	    }
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
	        ip = request.getHeader("WL-Proxy-Client-IP");
	    }
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
	        ip = request.getRemoteAddr();
	    }
	    return ip.equals("0:0:0:0:0:0:0:1")?"127.0.0.1":ip;
	}	
	
	
	/**
	 * 根据第三方服务获取json字符串 并进行utf8 输码
	 * @param url json第三方服务的连接
	 * @return
	 * @throws Exception 
	 * 
	 */
	public static String getJsonStringByUrl(String urlPath) throws Exception{
		
		
		String jsonString = null;
		try {
			URL url = new URL(urlPath);
			HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();		
			httpURLConnection.setConnectTimeout(10000);//读取
			httpURLConnection.setReadTimeout(10000);
			httpURLConnection.connect();
			InputStream inputStream = httpURLConnection.getInputStream();//读取输入流
			//字符编码转换
			Reader reader = new InputStreamReader(inputStream,"UTF-8");
			BufferedReader bufferReader = new BufferedReader(reader);
			String str = null;
			
			StringBuffer stringBuffer = new StringBuffer();//创建字符缓存区读字符流
			while((str = bufferReader.readLine())!= null){
				
				stringBuffer.append(str);
			}
			//httpURLConnection.disconnect();
			jsonString = stringBuffer.toString();
		} catch (Exception e) {
			log.info("查询IP异常");
		}
		
			return jsonString;
		
		
		
		
		
		
		
		
	}
	
	
	/**
	 * 解释json字符串并输入对象
	 * @param jsonStr
	 */
	public static JSONObject jsonToObject(String jsonStr){
		
		
		JSONObject ipInfoJSONObject = JSONObject.parseObject(jsonStr);//从json对象中获取
//		JSONObject dataJSONObject = ipInfoJSONObject.getJSONObject("data");
//		String country=dataJSONObject.getString("country");
//		String area = dataJSONObject.getString("area");
//		String region = dataJSONObject.getString("region");
//		
//		String city = dataJSONObject.getString("city");
		
		
		return ipInfoJSONObject;
	}
	
	
	
	
	
	
	/**
	 * 日期转换为 (yyyy-MM-dd HH) 格式 
	 * @return
	 */
	public static String getOrderDate(){
		
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH");
		String date = simpleDateFormat.format(new Date());
		return date;
		
	}
	
	/**
	 * 日期转换为 (yyyy-MM-dd HH) 格式 
	 * @return
	 */
	public static Date getOrderDate(String date) throws Exception{
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH");
		return simpleDateFormat.parse(date);
		
	}
	
	/**
	 * 日期转换为 (yyyy-MM-dd) 格式 
	 * @return
	 */
	public static String getOrderDate(Date date){		
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		String dateForm = simpleDateFormat.format(date);
		return dateForm;
		
	}

	/**
	 * 日期转换为 对应的格式 
	 * @param date 时间
	 * @param format 格式 ,输入格式如：yyyy-MM-dd HH:mm:ss
	 * @return 对应格式的时间 Sting
	 */
	public static String getFormatDate(Date date, String format) {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
		return simpleDateFormat.format(date);			
	}
	
	/**
	 * 日期转换为 对应的格式 
	 * @param date 时间
	 * @param format 格式 ,输入格式如：yyyy-MM-dd HH:mm:ss
	 * @return 对应格式的时间 Date
	 * @throws ParseException 
	 */
	public static Date getParseDate(String date, String format) throws ParseException{
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
		return simpleDateFormat.parse(date);
	}
	
	/**
	 * 获取当前时间
	 * <br/>格式是： yyyy-MM-dd HH:mm:ss
	 * @return 当前时间
	 */
	public static Date getNowTime() {
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String nowStr = format.format(new Date());
		try {
			return format.parse(nowStr);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 
	 * 字节数组转数字
	 * @param b
	 * @param offset
	 * @return
	 */
	public static int byteArrayToInt(byte[] b, int offset) {
        int value = 0;
        for (int i = 0; i < 4; i++) {
            int shift = (4 - 1 - i) * 8;
            value += (b[i + offset] & 0x000000FF) << shift;
        }
        return value;
   }
	
	public static Object nullConvertToEmpty(Object obj){
		return obj==null?"":obj;
	}
	
	public static String sendAndReturnMsg(String mobiles,String content,boolean needstatus,String product,String extno){
		String returnString ="";
		try {
			returnString = HttpSender.batchSend(SmsConstants.SMS_URL, SmsConstants.SMS_ACCOUNT, SmsConstants.SMS_PSWT, mobiles, content, needstatus, product, extno);
			System.out.println(returnString);
			//TODO 处理返回值,参见HTTP协议文档
		} catch (Exception e) {
			//TODO 处理异常
			e.printStackTrace();
		}
		
		return returnString;
	}
	
    /** 
     * 创建指定数量的随机字符串 
     * @param numberFlag 是否是数字 
     * @param length 
     * @return 
     */  
    public static String createRandom(boolean numberFlag, int length){  
     String retStr = "";  
     String strTable = numberFlag ? "1234567890" : "1234567890abcdefghijkmnpqrstuvwxyz";  
     int len = strTable.length();  
     boolean bDone = true;  
     do {  
      retStr = "";  
      int count = 0;  
      for (int i = 0; i < length; i++) {  
    	  double dblR = Math.random() * len;  
    	  int intR = (int) Math.floor(dblR);  
    	  char c = strTable.charAt(intR);  
       if (('0' <= c) && (c <= '9')) {  
    	   count++;  
       }  
       		retStr += strTable.charAt(intR);  
      	}  
      	if (count >= 2) {  
      		bDone = false;  
      	}  
     } while (bDone);  
     
     return retStr;  
    }  
    
    
    public static boolean isMobileNO(String mobiles){  
    	  Pattern p = Pattern.compile("^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$"); 
    	  Matcher m = p.matcher(mobiles);  
    	  return m.matches();  
    }  
	
	
	/**
	 * 生成排序语句
	 * @param args
	 */
	public static String getOrderByHql(Map<String,String> orderMap,String status){
		StringBuffer orderBuffer = new StringBuffer(" order by "); 
		int index= 0;
		if(orderMap!=null&&orderMap.keySet().size()>0){
			for(Entry<String, String> entry:orderMap.entrySet()){
				
				orderBuffer.append(entry.getKey()+" "+entry.getValue());
				if(index!= orderMap.keySet().size()-1){
					orderBuffer.append(",");
				}
				index++;
			}
			
		}else{
			if(status==null||"".equals(status)){
				orderBuffer.append("createDate desc");
			}else if(status.equals(OrderConstants.ORDER_ESTIMATED)
					||status.equals(OrderConstants.ORDER_ORDERED)
					||status.equals(OrderConstants.ORDER_ESTIMATED_OR_NOTESTIMATED)){
				orderBuffer.append("orderDate desc");
			}else if(status.equals(OrderConstants.ORDER_IN_SHOPPINGCART)){
				orderBuffer.append("createDate desc");
			}else if(status.equals(OrderConstants.ORDER_DISABLE)){
				orderBuffer.append("");
			}
		}
		return orderBuffer.toString();
	}
	
	
	 /**
	  * 两个日期字符串比较
	  * @param DATE1
	  * @param DATE2
	  * @return
	  */
	 public static int compare_date(String DATE1, String DATE2) {
	       
		
	        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	        try {
	            Date dt1 = df.parse(DATE1);
	            Date dt2 = df.parse(DATE2);
	            if (dt1.getTime() > dt2.getTime()) {
	                //System.out.println("dt1 在dt2前");
	                return 1;
	            } else if (dt1.getTime() < dt2.getTime()) {
	                //System.out.println("dt1在dt2后");
	                return -1;
	            } else {
	                return 0;
	            }
	        } catch (Exception exception) {
	            exception.printStackTrace();
	        }
	        return 0;
	    }
	 
	 /**
	  * 去掉域名的http和最后的/
	  * @param domain
	  * @return
	  */
	 public static String urlFilter(String domain){
		 	Pattern r = Pattern.compile(BusinessUtils.HTTP_PATTERN,Pattern.CASE_INSENSITIVE);
			
			Matcher m=r.matcher(domain);
			
			return m.replaceAll("");
	 }
	 
	 
	 /**
	  * 去掉www
	  * @param domain
	  * @return
	  */
	 public static String wwwFilter(String domain){
		 	Pattern r = Pattern.compile(BusinessUtils.WWW_PATTERN,Pattern.CASE_INSENSITIVE);
		 	
		 	Matcher m = r.matcher(domain);
		 	
		 	return m.replaceAll("");
		 	
		 
	 }
	 
	 /**
	  * 读取磁盘文件上的json聊天记录，并转化为json对象列表
	  * @param filePath
	  * @return
	  */
	 public static List<JSONObject> readJsonListFromFile(String filePath){
		 List<JSONObject> jsonList = new ArrayList<JSONObject>();
		 try {
		 InputStream input = new FileInputStream(new File(filePath));
		 List<String> jsonLines = IOUtils.readLines(input,"UTF-8");
		 for(String jsonLine:jsonLines){
			 JSONObject jsonObject = (JSONObject) JSON.parse(jsonLine);
			 jsonList.add(jsonObject);
		 }
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 	return jsonList;
	 }
	 
	
	
	
	public static void main(String[] args) {
		//System.out.println(createRandom(true,6));
//		String domain="http://www.domain.com/";
//		domain =BusinessUtils.urlFilter(domain);
//		System.out.println(domain);
//		domain =BusinessUtils.wwwFilter(domain);
//		System.out.println(BusinessUtils.wwwFilter(domain));
		//String aaa="\u5317\u4eac\u5e02";
//		try {
//			jsonToObject(new String(getJsonStringByUrl("http://ip.taobao.com/service/getIpInfo.php?ip=206.220.42.25").getBytes("UTF-8"),"utf-8"));
//			//System.out.println(new String(aaa));
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		
		List<JSONObject> jsonObjects = readJsonListFromFile("F:\\2017081217");
		for(JSONObject jsonObject:jsonObjects){
			System.out.println(jsonObject);
		}
	}

}
